﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ICSharpCode.SharpZipLib.Zip;
using COM.Web;
using ICSharpCode.SharpZipLib.GZip;
using WebApp.Web.Service;
using COM.Data;
using WebApp.Service;

namespace WebApp.Web.Controllers
{
    public class FileController : Controller
    {
        private IUploadFileService uploadFileService = Unity.Instance.GetService<IUploadFileService>();

        [HttpPost]
        public ActionResult Upload(string qqfilename)
        {
            try
            {
                if (Request.Files.Count != 1)
                    throw new ApplicationException("上传文件应有一个文件流.");

                HttpPostedFileBase postFile = Request.Files[0];
                if (postFile.ContentLength == 0)
                    throw new ApplicationException("空文件");

                var fileItemID = this.uploadFileService.UploadFile("TempFile", qqfilename, Request.Files[0]);
                return Json(new { success = true, fileItemID = fileItemID,message="上传成功." }, "application/json");
            }
            catch (Exception exception)
            {
                string format = "FileUploadError:{0}={1}\r\n{2}.Message:{3}\r\nStack:{4}\r\n";
                string errorInfo = string.Format(format, this.Request.HttpMethod, this.Request.Url, exception.GetType().Name, exception.Message, exception.StackTrace);
                var logErrorService = Unity.Instance.GetService<COM.Service.ILogErrorService>();
                logErrorService.LogWebAppError(errorInfo);
                return Json(new { success = false, fileItemID=Guid.Empty, message = "上传失败!" }, "application/json");
            }
        }

        public ActionResult Index(Guid id)
        {
            var runtimeService = Unity.Instance.GetService<IRuntime>();
            var userID = runtimeService.Permission.CurrentUser.UserID;
            var httpRequestService = Unity.Instance.GetService<IHttpRequestService>();
            var ip = httpRequestService.ClientIP;
            var fileInfo = this.uploadFileService.GetFileInfoByID(id);
            var tempFileService = Unity.Instance.GetService<ITempFileService>();
            var tempFile = tempFileService.GetNotExpiredTempFileByFileItemID(id);
            if (tempFile == null)
                return this.RedirectToAction("Download", "TempFile", new { id = "FileIndex" });

            var filePath = fileInfo.Item1;
            var fileName = fileInfo.Item2;
            using (var iStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
            {
                var dataToRead = iStream.Length; //Total bytes to read
                //Response.ContentType = "application/octet-stream; Charset=UTF8";
                //Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                this.Response.AddHeader("content-type", "application/octet-stream");
                this.Response.AddHeader("content-length", dataToRead.ToString());
                this.Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
                var beginDate = DateTime.Now;
                bool isCancel = false;
                while (!isCancel && dataToRead > 0)
                {
                    if (Response.IsClientConnected)  //Verify that the client is connected.
                    {
                        byte[] buffer = new Byte[4096];  //Buffer to read 10K bytes in chunk
                        var length = iStream.Read(buffer, 0, 4096);  //Read the data in buffer.
                        Response.OutputStream.Write(buffer, 0, length); //Write the data to the current output stream.
                        Response.Flush();  //Flush the data to the HTML output.
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        if (dataToRead > 0)
                            isCancel = true;
                    }
                }

                this.Response.End();
                this.Response.Close();
                var fileItemService = Unity.Instance.GetService<IFileItemService>();
                fileItemService.CreateFileItemDownload(fileItemID: id, ip:ip, beginDate: beginDate, endDate: DateTime.Now, isDownloaded: !isCancel, userID: userID);
            }

            return null;
        }

    }



}
